<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.productMaterialConfig_add" @click="addBtn">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.productMaterialConfig_delete" @click="handleDelete">删 除 </el-button>
        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport('all')">导入</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.productMaterialConfig_view" @click="rowView(row)">详情</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.productMaterialConfig_edit" @click="rowUpdate(row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.productMaterialConfig_delete" @click="$refs.crud.rowDel(row, index)">删除</el-button>
      </template>
    </avue-crud>
    <el-dialog
      v-dragDirectives
      ref="dialog"
      :title="dialogTitle"
      append-to-body
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      top="5vh"
      width="70%"
      @close="closeDialog"
    >
      <avue-form ref="basicInfoForm" v-if="showDialog" v-model="form" :option="dialogOption"></avue-form>
      <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>生产用料配置</h3>
      <el-row style="margin-bottom: 10px">
        <el-button v-if="dialogTitle != '详情'" type="primary" size="small" @click="addMaterial('partModal')">添加物料</el-button>
        <el-button v-if="dialogTitle != '详情'" type="danger" size="small" icon="el-icon-delete" @click="productInfoDelete">删 除</el-button>
        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport('detail')">导入</el-button>
        <el-button type="success" size="small" @click="materialProcessConfig('detail')">用料工序配置</el-button>
      </el-row>
      <el-table v-loading="loading" ref="productInfoCrud" height="500px" :data="productInfoList" border style="width: 100%" @selection-change="basicInfoSelectionChange">
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column type="index" width="50" align="center"></el-table-column>
        <el-table-column v-for="item in productInfoOption.column" :label="item.label" :prop="item.prop" :key="item.prop">
          <template slot-scope="scope">
            <span v-if="item.prop === 'quantity'">
              <el-input-number v-model="scope.row.quantity" name="quantity" :controls="false" style="width: 100%" :disabled="dialogTitle == '详情'"></el-input-number>
            </span>
            <span v-else-if="item.prop === 'sectionId'">
              <el-select v-model="scope.row.sectionId" placeholder="请选择 用料工段" :disabled="dialogTitle == '详情'" @change="sectionChange(scope.$index)">
                <el-option v-for="item in workSectionList" :key="item.sectionId" :label="item.sectionName" :value="item.sectionId"></el-option>
              </el-select>
            </span>
            <span v-else-if="item.prop === 'materialProcessName'">
              <el-select
                v-model="scope.row.materialProcessName"
                placeholder="请选择 生产工序"
                :clearable="true"
                :disabled="dialogTitle == '详情'"
                @focus="materialProcessChange(scope.row.sectionId)"
              >
                <el-option v-for="item in workProcessList" :key="item.id" :label="item.materialProcessName" :value="item.materialProcessName"></el-option>
              </el-select>
            </span>
            <span v-else-if="item.prop === 'isKeyMaterial'">
              <el-select v-model="scope.row.isKeyMaterial" placeholder="请选择" :disabled="dialogTitle == '详情'">
                <el-option label="是" :value="true"> </el-option>
                <el-option label="否" :value="false"> </el-option>
              </el-select>
            </span>
            <span v-else-if="item.prop === 'isBackflush'">
              <el-select v-model="scope.row.isBackflush" placeholder="请选择" :disabled="dialogTitle == '详情'">
                <el-option label="是" :value="true"> </el-option>
                <el-option label="否" :value="false"> </el-option>
              </el-select>
            </span>
            <span v-else-if="item.prop === 'backflushWarehouseId'">
              <el-select v-model="scope.row.backflushWarehouseId" placeholder="请选择" :clearable="true" :disabled="dialogTitle == '详情'">
                <el-option v-for="item in warehouseList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200" v-if="dialogTitle != '详情'">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="productInfoRowDel(scope.row, scope.$index)">删除</el-button>
            <el-button type="text" size="small" @click="handleAddMaterial(scope.row, scope.$index)">添加替代料</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" type="primary" size="small" @click="submit"><i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
        <el-button v-if="dialogTitle === '编辑'" type="primary" size="small" @click="submit"><i class="el-icon-circle-check"></i><span>修 改</span> </el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :key="timer" :option="tableOption" @getSelectedRows="getSelectedRows" @newKey="newKey"></common-modal-template>
    <importDialogComp
      :title="importConfig.title"
      :url="importConfig.importUrl"
      :params="importConfig.params"
      :export-name="importConfig.exportName"
      :visible.sync="importConfig.show"
      @submit="codeClose"
    ></importDialogComp>
    <el-dialog
      class="replaceDialog"
      ref="dialog"
      title="添加替代料"
      append-to-body
      :visible.sync="alternativeMaterialsDialog"
      :close-on-click-modal="false"
      top="5vh"
      width="70%"
      @close="replaceClose"
    >
      <avue-form v-if="alternativeMaterialsDialog" ref="partForm" v-model="partForm" :option="partOption"></avue-form>
      <el-row style="margin-bottom: 10px">
        <el-button v-if="dialogTitle != '详情'" type="primary" icon="el-icon-plus" size="small" @click="addReplace">新增行</el-button>
      </el-row>
      <el-table height="500px" :data="alternativeMaterialsList" border style="width: 100%">
        <el-table-column type="index" width="50" align="center"></el-table-column>
        <el-table-column v-for="item in alternativeMaterialsOption" :label="item.label" :prop="item.prop" :key="item.prop">
          <template slot-scope="scope">
            <span v-if="item.prop === 'partNo'">
              <el-input v-model="scope.row.partNo" :disabled="dialogTitle == '详情'">
                <el-button slot="append" icon="el-icon-search" @click="openSelectReplaceModal(scope.$index)"></el-button>
              </el-input>
            </span>
            <span v-else-if="item.prop === 'quantity'">
              <el-input-number v-model="scope.row.quantity" name="quantity" :controls="false" style="width: 100%" :disabled="dialogTitle == '详情'"></el-input-number>
            </span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200" v-if="dialogTitle != '详情'">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="replacePartRowDel(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="alternativeMaterialsDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
        <el-button type="primary" size="small" @click="submitReplacePart"><i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
      </span>
    </el-dialog>
    <el-dialog ref="dialog" title="新增用料工序" append-to-body :visible.sync="materialProcessDialog" :close-on-click-modal="false" top="5vh" width="50%" @close="replaceClose">
      <el-row style="margin-bottom: 10px">
        <el-button type="primary" icon="el-icon-plus" size="small" @click="addProcessConfig">新增行</el-button>
      </el-row>
      <el-table ref="elTable" height="500px" :data="materialProcessConfigData" border style="width: 100%">
        <el-table-column type="index" width="50" align="center"></el-table-column>
        <el-table-column label="生产工段" prop="sectionId">
          <template slot-scope="scope">
            <el-select v-model="scope.row.sectionId" placeholder="请选择 生产工段" :disabled="!scope.row.isEdit" style="width: 100%">
              <el-option v-for="item in processWorkSectionList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="用料工序" prop="materialProcessName">
          <template slot-scope="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.materialProcessName"></el-input>
            <span v-else>{{ scope.row.materialProcessName }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-button v-if="scope.row.isEdit" size="small" type="text" icon="el-icon-plus" @click="saveProcessConfig(scope.row, scope.$index)">保存</el-button>
            <el-button v-if="!scope.row.isEdit" size="small" type="text" icon="el-icon-edit" @click="editProcessConfig(scope.$index)">编辑</el-button>
            <el-button size="small" type="text" icon="el-icon-delete" @click="processConfigRowDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="materialProcessDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>
<script>
import {
  getList,
  getDetail,
  addOrUpdate,
  remove,
  getSectionByPartId,
  getDetailByPartNo,
  getWarehouseList,
  materialProcessSubmit,
  materialProcessRemove,
  getAllWorkSection,
  getConfiguration,
  getMaterialProcessAll
} from '@/api/product/product-material-config';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { getList as getBomList, getReplacementList } from '@/api/admin/bom';
import TimelyControlDialog from '@/views/product/components/timelyControlDialog';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import importDialogComp from '@/components/dialog/import/index.vue';
import { replace } from 'lodash-es';
export default {
  name: 'ProductProductMaterialConfig',
  components: {
    TimelyControlDialog,
    CommonModalTemplate,
    userTableConfig,
    importDialogComp
  },
  mixins: [userConfig()],
  data() {
    var validateQuantity = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入单位用量'));
      } else {
        if (value <= 0) {
          callback(new Error('单位用量不能小于等于0'));
        } else {
          callback();
        }
      }
    };
    return {
      pageCode: 'PRODUCT_MATERIAL_CONFIG',
      form: {},
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 360px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        menuWidth: 200, //弹框内字段宽度属性
        dialogWidth: 880, //弹框宽度属性
        labelWidth: '110',
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '产品名称',
            prop: 'productPartName'
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            search: true,
            disabled: false
          },
          {
            label: '产品类型',
            prop: 'partType',
            type: 'select',
            search: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '产品型号',
            prop: 'productPartModel',
            search: true
          },
          {
            label: '创建人',
            prop: 'createUserName'
          },
          {
            label: '创建时间',
            prop: 'createTime'
          }
        ]
      },
      dialogTitle: '新增',
      showDialog: false,
      dialogOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '80',
        column: [
          {
            label: '产品编码',
            prop: 'productPartNo',
            type: 'search',
            span: 8,
            labelWidth: '85',
            placeholder: '请选择 产品编码',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择产品编码',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              if (this.dialogTitle === '新增') {
                this.openProductCommonModal();
              }
            }
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            span: 8,
            disabled: true
          },
          {
            label: '产品类型',
            prop: 'partType',
            type: 'select',
            span: 8,
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            disabled: true
          }
        ]
      },
      data: [],
      productInfoOption: {
        height: 500,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        cellBtn: true,
        menuWidth: 280,
        column: [
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料规格',
            prop: 'partSpec'
          },
          {
            label: '用料工段',
            prop: 'sectionId',
            cell: true,
            type: 'select',
            dicData: [],
            rules: [
              {
                required: true,
                message: '请输入用料工段',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '生产工序',
            prop: 'materialProcessName',
            cell: true,
            type: 'select',
            dicData: [],
            rules: [
              {
                required: true,
                message: '请选择生产工序',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '单位用量',
            prop: 'quantity',
            cell: true,
            type: 'number',
            rules: [{ validator: validateQuantity, trigger: 'blur' }]
          },
          {
            label: '是否关键料',
            prop: 'isKeyMaterial'
          },
          {
            label: '是否倒冲',
            prop: 'isBackflush'
          },
          {
            label: '倒冲仓库',
            prop: 'backflushWarehouseId'
          }
          // {
          //   label: 'json',
          //   prop: 'replacePartNo',
          //   cell: false,
          //   hide: true
          // },
          // {
          //   label: '替代料编码',
          //   prop: 'replacementPartCode',
          //   cell: false,
          //   hide: false
          // },
          // {
          //   label: '替代料型号',
          //   prop: 'replacementPartModel',
          //   cell: false,
          //   hide: false
          // }
        ]
      },
      productInfoList: [],
      productInfoKey: 'init',
      tableOption: {},
      timer: new Date().getTime(),
      basicInfoSelectionList: [],
      processId: '', //工艺ID,
      workSectionList: [],
      selectTimeControlIndex: 0,
      addPartType: '',
      selectSectionDialogForm: {},
      selectSectionOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '用料工段',
            type: 'select',
            span: 24,
            prop: 'sectionId',
            dicData: [],
            rules: [
              {
                required: true,
                message: '请选择用料工段',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      importConfig: {
        show: false,
        importUrl: '/api/mes-product/key/material/config/import',
        exportName: '产品用料导入模版.xlsx',
        formData: {
          req: []
        },
        params: {},
        title: '产品用料导入'
      },
      partForm: {},
      partOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '80',
        column: [
          {
            label: '物料编码',
            prop: 'productPartNo',
            span: 8,
            labelWidth: '85',
            disabled: true
          },
          {
            label: '物料规格',
            prop: 'partSpec',
            span: 8,
            labelWidth: '85',
            disabled: true
          }
        ]
      },
      alternativeMaterialsList: [],
      alternativeMaterialsDialog: false,
      alternativeMaterialsOption: [
        {
          label: '替代物料编码',
          prop: 'partNo'
        },
        {
          label: '替代物料名称',
          prop: 'partName'
        },
        {
          label: '替代物料规格',
          prop: 'partSpec'
        },
        {
          label: '单位用量',
          prop: 'quantity'
        }
      ],
      replaceRowIndex: '',
      importType: '',
      deletedIds: [],
      warehouseList: [],
      materialProcessDialog: false,
      materialProcessConfigData: [],
      processWorkSectionList: [],
      workProcessList: []
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    getWarehouseList().then(
      (res) => {
        this.warehouseList = this._get(res, 'data.data', []);
      },
      (error) => {
        this.warehouseList = [];
      }
    );
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    basicInfoIndex() {
      let indexs = [];
      this.basicInfoSelectionList.forEach((ele) => {
        indexs.push(ele.$index);
      });
      return indexs;
    }
  },
  methods: {
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      if (this.query.productPartNo) {
        this.query['partNo'] = this.query.productPartNo;
        delete this.query.productPartNo;
      }
      if (this.query.productPartModel) {
        this.query['partModel'] = this.query.productPartModel;
        delete this.query.productPartModel;
      }
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this._forEach(this.data, (item) => {
          item.status = String(item.status);
        });
        this.loading = false;
        this.selectionClear();
      });
    },
    addBtn() {
      this.showDialog = true;
      this.dialogTitle = '新增';
      this.$nextTick(() => {
        this.$refs.basicInfoForm.allDisabled = false;
      });
    },
    /**
     * 提交
     */
    submit() {
      this.$refs.basicInfoForm.validate((valid, done) => {
        if (valid) {
          if (this.productInfoList.length === 0) {
            this.$message({
              type: 'warning',
              message: '请添加生产用料！'
            });
            return;
          }
          for (let i = 0; i < this.productInfoList.length; i++) {
            if (!this.productInfoList[i].sectionId) {
              this.$message({
                type: 'warning',
                message: `物料编码为${this.productInfoList[i].partNo}的用料工段不能为空！`
              });
              return;
            }
            if (!this.productInfoList[i].quantity && this.productInfoList[i].quantity != 0 && this.productInfoList[i].partSubType !== 'INDIRECT') {
              this.$message({
                type: 'warning',
                message: `物料编码为${this.productInfoList[i].partNo}的单位用量不能为空！`
              });
              return;
            }
            if (this.productInfoList[i].quantity <= 0) {
              this.$message({
                type: 'warning',
                message: `物料编码为${this.productInfoList[i].partNo}的单位用量不能小于等于0！`
              });
              return;
            }
            if (this.productInfoList[i].isBackflush && !this.productInfoList[i].backflushWarehouseId) {
              this.$message({
                type: 'warning',
                message: `物料编码为${this.productInfoList[i].partNo}的物料已开启倒冲，倒冲仓库不能为空！`
              });
              return;
            }
            for (let j = i + 1; j < this.productInfoList.length; j++) {
              if (this.productInfoList[i].partNo === this.productInfoList[j].partNo && this.productInfoList[i].sectionId === this.productInfoList[j].sectionId) {
                this.$message({
                  type: 'warning',
                  message: `多个物料编码为${this.productInfoList[i].partNo}的用料工段不能被重复选择！`
                });
                return;
              }
            }
          }
          let params = {};
          if (this.dialogTitle === '新增') {
            let materialControls = [];
            this._forEach(this.productInfoList, (item, index) => {
              let workSectionObj = this._find(this.workSectionList, { sectionId: item.sectionId });
              let warehouseObj = this._find(this.warehouseList, { id: item.backflushWarehouseId });
              let materialProcessObj = this._find(this.workProcessList, { materialProcessName: item.materialProcessName });
              let params = {
                keyMaterialConfigId: item.partMasterId,
                sequence: index + 1,
                partNo: item.partNo,
                partName: item.partName,
                partModel: item.partModel ? item.partModel : '',
                partSpec: item.partSpec,
                quantity: item.quantity,
                sectionId: item.sectionId,
                sectionName: workSectionObj ? workSectionObj.sectionName : '',
                materialProcessConfigurationId: materialProcessObj ? materialProcessObj.id : '',
                materialProcessName: item.materialProcessName,
                isBackflush: item.isBackflush,
                backflushWarehouseId: item.backflushWarehouseId,
                backflushWarehouseCode: warehouseObj ? warehouseObj.code : '',
                replacePartNo: item.replacePartNo,
                timeConditions: item.timeConditions
              };
              materialControls.push(params);
            });
            params = {
              type: 'PRODUCT',
              partMasterId: this.form.partMasterId,
              productPartNo: this.form.productPartNo,
              productPartName: this.form.productPartName,
              productPartModel: this.form.productPartModel,
              keyMaterialConfigDetailDtoList: materialControls
            };
          } else {
            this._forEach(this.productInfoList, (item, index) => {
              item.sequence = index + 1;
              item.processId = this.processId;
              item.controlType = 'ROUTE';
              item.subType = 'PRODUCT';
              let workSectionObj = this._find(this.workSectionList, { sectionId: item.sectionId });
              item.sectionName = workSectionObj ? workSectionObj.sectionName : '';
              let warehouseObj = this._find(this.warehouseList, { id: item.backflushWarehouseId });
              item.backflushWarehouseCode = warehouseObj ? warehouseObj.code : '';
              let materialProcessObj = this._find(this.workProcessList, { materialProcessName: item.materialProcessName });
              item.materialProcessConfigurationId = materialProcessObj ? materialProcessObj.id : '';
            });
            params = this.form;
            params.keyMaterialConfigDetailDtoList = this.productInfoList;
            params['deletedIds'] = this.deletedIds;
          }
          addOrUpdate(params).then(
            (res) => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              this.showDialog = false;
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    /**
     * 查看详情数据
     */
    rowView(row) {
      this.showDialog = true;
      this.dialogTitle = '详情';
      this.$nextTick(() => {
        this.$refs.basicInfoForm.allDisabled = true;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.form.partType = row.partType;
        this.productInfoOption.menu = false;
        getSectionByPartId(row.partMasterId).then((res) => {
          let data = this._get(res, 'data.data.sections', []);
          if (data != null) {
            this.workSectionList = data;
          } else {
            this.workSectionList = [];
          }

          this.productInfoList = this._get(this.form, 'details', []);
          this._forEach(this.productInfoList, (item) => {
            try {
              item.replacementPartCode = item.replacePartNo ? (JSON.parse(item.replacePartNo) || []).map((item) => item.partCode).join(',') : '';
              item.replacementPartSpec = item.replacePartNo ? (JSON.parse(item.replacePartNo) || []).map((item) => item.partSpec).join(',') : '';
            } catch (error) {
              console.log('error', error);
            }
          });
        });
      });
    },
    rowUpdate(row) {
      this.showDialog = true;
      this.dialogTitle = '编辑';
      this.$nextTick(() => {
        this.$refs.basicInfoForm.allDisabled = true;
      });
      this.productInfoOption.menu = true;
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        getSectionByPartId(row.partMasterId).then((res) => {
          let data = this._get(res, 'data.data.sections', []);
          if (data != null) {
            this.workSectionList = data;
          } else {
            this.workSectionList = [];
          }
          this.productInfoList = this._get(this.form, 'details', []);
        });
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    closeDialog() {
      this.$refs.basicInfoForm.resetFields();
      this.form = {};
      this.productInfoList = [];
      this.deletedIds = [];
      let workSectionIdColumn = this.findObject(this.productInfoOption.column, 'sectionId');
      workSectionIdColumn.dicData = [];
    },
    /**
     * 打开物料选择模态框
     */
    openProductCommonModal() {
      this.modalName = 'productModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=true',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料分类',
            prop: 'categoryName'
          },
          {
            label: '物料规格',
            prop: 'partSpec'
          },
          {
            label: '物料类型',
            prop: 'partType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },
    openSelectReplaceModal(index) {
      this.replaceRowIndex = index;
      this.addMaterial('replacePartModal');
    },
    /**
     * 添加物料
     */
    addMaterial(type) {
      if (!this.form.productPartNo) {
        this.$message({
          type: 'warning',
          message: '请先选择产品！'
        });
        return;
      }
      this.modalName = type;
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料',
        url: '/api/mes-admin/part-master/page',
        isPage: true,
        rowSelectionType: type === 'replacePartModal' ? 'single' : 'multiple',
        isDefaultLoad: true,
        selectOption: {
          isMark: true
        },
        selectable: (row, index) => {
          return !this.productInfoList.map((item) => item.partMasterId).includes(row.id);
        },
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料分类',
            prop: 'categoryName'
          },
          {
            label: '物料规格',
            prop: 'partSpec'
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },
    /**
     * 双击模态框行
     */
    getSelectedRows(row) {
      switch (this.modalName) {
        case 'productModal':
          this.form.productPartId = row.id;
          this.form.productPartNo = row.partNo;
          this.form.productPartName = row.name;
          this.form.productPartModel = row.partModel;
          this.form.partType = row.partType;
          this._forEach(this.productInfoList, (item) => {
            item.sectionId = '';
          });
          getSectionByPartId(this.form.productPartId).then((res) => {
            let data = this._get(res, 'data.data.sections', []);
            if (data != null) {
              this.workSectionList = data;
            } else {
              this.workSectionList = [];
            }
          });
          break;
        case 'partModal':
          for (let i = 0; i < row.length; i++) {
            this.productInfoList.push({
              $index: this.productInfoList.length,
              partMasterId: row[i].id,
              partNo: row[i].partNo,
              partName: row[i].name,
              partModel: row[i].partModel ? row[i].partModel : '',
              partSpec: row[i].partSpec,
              quantity: undefined,
              sectionId: '',
              isKeyMaterial: false,
              isBackflush: false
            });
          }
          break;
        case 'replacePartModal':
          let obj = this._find(this.alternativeMaterialsList, { partNo: row.partNo });
          if (obj) {
            this.$message({
              type: 'warning',
              message: '已存在相同物料，请重新选择！'
            });
            return;
          }
          this.$set(this.alternativeMaterialsList[this.replaceRowIndex], 'partNo', row.partNo);
          this.$set(this.alternativeMaterialsList[this.replaceRowIndex], 'partName', row.name);
          this.$set(this.alternativeMaterialsList[this.replaceRowIndex], 'partModel', row.partModel ? row.partModel : '');
          this.$set(this.alternativeMaterialsList[this.replaceRowIndex], 'partSpec', row.partSpec);
          this.$set(this.alternativeMaterialsList[this.replaceRowIndex], 'quantity', undefined);
          // const index = this.selectTimeControlIndex;
          // const replacementList = row.map((item) => ({
          //   partNo: item.partNo,
          //   partName: item.partName,
          //   rate: item.subsRate
          // }));
          // this.$set(this.productInfoList[index], 'replacePartNo', JSON.stringify(replacementList));
          // this.$set(this.productInfoList[index], 'replacementPartCode', replacementList.map((item) => item.partCode).join(','));
          // this.$set(this.productInfoList[index], 'replacementPartModel', replacementList.map((item) => item.partModel).join(','));
          // this.$set(this.productInfoList[index], 'isReplaceable', row.length > 0);
          // this.productInfoKey = new Date().getTime();
          break;
        default:
          break;
      }
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    productInfoRowClick(row) {
      this.rowIndex = row.$index;
    },
    productInfoRowSave(form, done) {
      done();
    },
    productInfoRowUpdate(form, index, done) {
      done();
    },
    productInfoRowDel(row, index) {
      if (row.id) {
        this.deletedIds.push(row.id);
      }
      this.productInfoList.splice(index, 1);
    },
    basicInfoSelectionChange(list) {
      this.basicInfoSelectionList = list;
    },
    productInfoDelete() {
      if (this.basicInfoSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this._forEach(this.basicInfoSelectionList, (item) => {
          if (item.id) {
            this.deletedIds.push(item.id);
          }
          let index = this.productInfoList.indexOf(item);
          this.productInfoList.splice(index, 1);
        });
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.$refs.productInfoCrud.clearSelection();
      });
    },

    // 添加替代料
    async handleAddMaterial(row, index) {
      this.alternativeMaterialsDialog = true;
      this.partForm.productPartNo = row.partNo;
      this.partForm.partSpec = row.partSpec;
      this.selectTimeControlIndex = index;
      this.alternativeMaterialsList = row.replacePartNo ? JSON.parse(row.replacePartNo) : [];
    },
    addReplace() {
      this.alternativeMaterialsList.push({
        partNo: '',
        partName: '',
        partSpec: '',
        rate: '',
        quantity: undefined
      });
    },
    replacePartRowDel(index) {
      this.alternativeMaterialsList.splice(index, 1);
    },
    submitReplacePart() {
      for (let i = 0; i < this.alternativeMaterialsList.length; i++) {
        if (!this.alternativeMaterialsList[i].partNo) {
          this.$message({
            type: 'warning',
            message: '替代物料编码不能为空！'
          });
          return;
        }
        if (!this.alternativeMaterialsList[i].quantity && this.alternativeMaterialsList[i].quantity != 0) {
          this.$message({
            type: 'warning',
            message: `物料编码为${this.alternativeMaterialsList[i].partNo}的单位用量不能为空！`
          });
          return;
        }
        if (this.alternativeMaterialsList[i].quantity <= 0) {
          this.$message({
            type: 'warning',
            message: `物料编码为${this.alternativeMaterialsList[i].partNo}的单位用量不能小于等于0！`
          });
          return;
        }
      }
      const index = this.selectTimeControlIndex;
      this.$set(this.productInfoList[index], 'replacePartNo', JSON.stringify(this.alternativeMaterialsList));
      this.alternativeMaterialsDialog = false;
    },
    replaceClose() {
      this.partForm = {};
      this.alternativeMaterialsList = [];
    },
    handleImport(type) {
      this.importConfig.show = true;
      this.importType = type;
      if (type === 'detail') {
        if (!this.form.productPartNo) {
          this.$message({
            type: 'warning',
            message: '请先选择产品！'
          });
          return;
        }
        this.importConfig.params = {
          productPartNo: this.form.productPartNo
        };
      } else {
        this.importConfig.params = {};
      }
    },
    codeClose(value, data, fileParams) {
      if (this.importType === 'all') {
        this.onLoad(this.page);
      } else {
        getDetailByPartNo(this.form.productPartNo).then((res) => {
          this.productInfoList = this._get(res, 'data.data.details', []);
        });
      }
    },
    materialProcessConfig() {
      this.materialProcessDialog = true;
      this.queryMaterialProcessAll();
      getAllWorkSection().then((res) => {
        this.processWorkSectionList = this._get(res, 'data.data', []);
      });
    },
    queryMaterialProcessAll() {
      getMaterialProcessAll().then(
        (res) => {
          this.materialProcessConfigData = this._get(res, 'data.data', []);
          this.map(this.materialProcessConfigData, (item) => {
            item.isEdit = false;
          });
        },
        (error) => {
          this.materialProcessConfigData = [];
        }
      );
    },
    addProcessConfig() {
      this.materialProcessConfigData.push({
        isEdit: true,
        sectionId: '',
        materialProcessName: ''
      });
    },
    sectionChange(index) {
      this.$set(this.productInfoList[index], 'materialProcessConfigurationId', '');
      this.$set(this.productInfoList[index], 'materialProcessName', '');
    },
    materialProcessChange(sectionId) {
      this.workProcessList = [];
      getConfiguration({ sectionId: sectionId }).then(
        (res) => {
          this.workProcessList = this._get(res, 'data.data', []);
        },
        (error) => {
          this.workProcessList = [];
        }
      );
    },
    saveProcessConfig(row, index) {
      let obj = this._find(this.processWorkSectionList, { id: row.sectionId });
      console.log(obj, this.processWorkSectionList);
      if (obj) {
        row['sectionName'] = obj.name;
      }
      materialProcessSubmit([row]).then((res) => {
        this.$message.success('保存成功');
        this.queryMaterialProcessAll();
      });
    },
    editProcessConfig(index) {
      this.$set(this.materialProcessConfigData[index], 'isEdit', true);
    },
    processConfigRowDel(row) {
      materialProcessRemove(row.id).then((res) => {
        this.$message.success('删除成功');
        this.queryMaterialProcessAll();
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.custom-title {
  font-size: 16px;
  font-weight: bold;
  .mr10 {
    margin-right: 10px;
  }
}
::v-deep .el-table__header {
  thead {
    th {
      background-color: #fafafa;
      padding: 8px 0;
      color: rgba(0, 0, 0, 0.85);
      font-size: 12px;
    }
  }
}
.replaceDialog {
  ::v-deep .el-input-group__append {
    padding: 0;
    .el-button {
      margin: 0;
      width: 50px;
    }
  }
}
</style>
